package com.ebring.shareEducation.service.impl;

import com.ebring.shareEducation.bean.*;
import com.ebring.shareEducation.bean.response.ReleaseUser;
import com.ebring.shareEducation.bean.OrderSheet;
import com.ebring.shareEducation.bean.Taskrelease;
import com.ebring.shareEducation.dao.*;
import com.ebring.shareEducation.dao.CompanyPayBillMapper;
import com.ebring.shareEducation.dao.OrderSheetMapper;
import com.ebring.shareEducation.dao.TaskreleaseMapper;
import com.ebring.shareEducation.dao.UserPayMapper;
import com.ebring.shareEducation.service.TaskreleaseService;
import com.ebring.shareEducation.utils.Md5Utils;
import com.ebring.shareEducation.utils.RspMsg;
import com.ebring.shareEducation.utils.UuidUtils;
import com.github.pagehelper.PageInfo;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.*;

import static com.ebring.shareEducation.utils.SendSMS.getStringDate;

@Service
@Transactional
public class TaskreleaseServiceImpl implements TaskreleaseService {

    @Autowired
    private TaskreleaseMapper taskreleaseMapper;


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderSheetMapper orderSheetMapper;

    @Autowired
    private UserPayMapper userPayMapper;
    @Autowired
    private CompanyPayBillMapper companyPayBillMapper;

/*    @Autowired
    CoinOrderService coinOrderService;*/


    // 后台审核查询所有的任务
    @Override
    public RspMsg<ReleaseUser> selectTaskrelease(String phone, String auditStates) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<ReleaseUser> taskalllist = taskreleaseMapper.selectTaskrelease(phone, auditStates);
        if (taskalllist.isEmpty() || taskalllist == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关任务");
            return rspMsg;
        }
        PageInfo<ReleaseUser> pageInfo = new PageInfo<>(taskalllist);
        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("taskalllist", taskalllist);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    // 修改任务

    @Override
    public RspMsg<Taskrelease> updateTaskrelease(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();

        int i = taskreleaseMapper.updateByPrimaryKeySelective(taskrelease);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("修改失败");
            return rspMsg;
        }
        rspMsg.setOK();
        return rspMsg;
    }


    @Override
    public RspMsg<Taskrelease> updateTaskreleaseorders(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        boolean flag = false;
        Taskrelease taskrelease1 = taskreleaseMapper.selectByPrimaryKey(new Taskrelease().setTaskReleaseId(taskrelease.getTaskReleaseId()));
        if ("0".equals(taskrelease.getRemark1())) {
            taskrelease1.setTaskStatus("1");

        } else if ("1".equals(taskrelease.getRemark1())) {
            taskrelease1.setTaskStatus("9");
            taskrelease1.setTaskorderStatus("9");
        } else if ("2".equals(taskrelease.getRemark1())) {
            taskrelease1.setTaskStatus("4");
            taskrelease1.setTaskorderStatus("4");

            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            taskrelease1.setRemark3(verifyCode);

            Example example = new Example(User.class);
            example.or().andEqualTo("userId", taskrelease.getUserId());
            User user = userMapper.selectByExample(example).get(0);
            String phone = user.getPhone();


            try {
                sendSMStask(phone, verifyCode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (taskrelease1 != null) {


            int i = taskreleaseMapper.updateByPrimaryKeySelective(taskrelease1);
            if (i == 0) {
                rspMsg.setError();
                rspMsg.setMsg("修改失败");
                return rspMsg;
            }

        }
        rspMsg.setOK();
        return rspMsg;
    }


    @Override
    public RspMsg<Taskrelease> updateTaskreleasecode(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
       /* boolean flag = false;
        boolean flags = false;
        Taskrelease taskrelease1 = taskreleaseMapper.selectByPrimaryKey(new Taskrelease().setTaskReleaseId(taskrelease.getTaskReleaseId()));

        taskrelease1.setTaskStatus("5");
        taskrelease1.setTaskorderStatus("5");
        String oldcode = taskrelease1.getRemark3();
        String newcode = taskrelease.getRemark3();

        if (newcode.equals(oldcode)) {
            flag = true;
            CompanyPayController companyPayController = new CompanyPayController();
            Example example = new Example(User.class);
            example.or().andEqualTo("userId", taskrelease1.getRemark2());
            User user = userMapper.selectByExample(example).get(0);
           // RspMsg rspMsg1 = companyPayController.payToEmployer(taskrelease1, user);
            CoinOrder coinOrder1 = new CoinOrder();
            coinOrder1.setUserId(taskrelease1.getRemark2());
            coinOrder1.setAmount(taskrelease1.getTaskPrice());
            coinOrder1.setTaskReleaseId(taskrelease1.getTaskReleaseId());
            coinOrder1.setGetType("4");
            RspMsg rspMsg1 = coinOrderService.addMoney(coinOrder1);//加金币
            if (rspMsg1.getResult() instanceof CompanyPay) {
                CompanyPay companyPay = (CompanyPay) rspMsg1.getResult();
                int insert = companyPayBillMapper.insertSelective(companyPay);
            }
            if (1 == rspMsg1.getCode()) {
                flags = true;
            } else {
                flags = false;
            }

            //支付方法

        }
        if (flag) {
            if (flags) {
                int i = taskreleaseMapper.updateByPrimaryKeySelective(taskrelease1);
                if (i > 0) {
                    rspMsg.setOK();
                    rspMsg.setMsg("支付成功");
                    return rspMsg;
                } else {
                    rspMsg.setError();
                    rspMsg.setMsg("修改失败");
                    return rspMsg;
                }
            } else {
                rspMsg.setError();
                rspMsg.setMsg("支付失败");
                return rspMsg;
            }
        } else {
            rspMsg.setError();
            rspMsg.setMsg("验证码错误");
            return rspMsg;
        }*/
       return null;

    }

    // 修改任务查看人数

    @Override
    public RspMsg<Taskrelease> updateNumber(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        Taskrelease taskrelease1 = selectUTaskrelease(taskrelease).getResult();
        String number = taskrelease1.getPenumber();
        taskrelease1.setPenumber(number + 1);
        int i = taskreleaseMapper.updateByPrimaryKeySelective(taskrelease);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("修改失败");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setMsg("修改成功");
        return rspMsg;

    }


    // 根据ID删除任务

    @Override
    public RspMsg<Taskrelease> deleteById(String taskreleaseId) {
        RspMsg rspMsg = new RspMsg();
        int i = taskreleaseMapper.deleteByPrimaryKey(taskreleaseId);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("删除失败");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setMsg("删除成功");
        return rspMsg;
    }

    // 新增任务
    @Override
    @Transactional
    public RspMsg<Taskrelease> insertTaskrelease(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        String taskReleaseId = UuidUtils.getNumberId(10);
        taskrelease.setTaskReleaseId(taskReleaseId);
        taskrelease.setCreateTime(UuidUtils.getdate());
        taskrelease.setExpirationTime("31");
        taskrelease.setTaskStatus("1");   //抢单状态
        //taskrelease.setUrgentState("1");//订单加急
        int i = taskreleaseMapper.insertSelective(taskrelease);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("任务添加失败");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setMsg("任务添加成功");
        rspMsg.setResult(taskReleaseId);
        return rspMsg;
    }

    // 查询用户的任务
    @Override
    public RspMsg<Taskrelease> selectUTaskrelease(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        ReleaseUser releaseList = new ReleaseUser();
        if (taskrelease != null) {
            releaseList = taskreleaseMapper.selectUTaskrelease(taskrelease);
            if (releaseList == null) {
                rspMsg.setOK();
                rspMsg.setMsg("未找到相关任务");
                return rspMsg;
            }
            map.put("releaseList", releaseList);
            rspMsg.setOK();
            rspMsg.setResult(map);
        }
        return rspMsg;
    }


    // 查询用户的任务
    @Override
    public RspMsg<Taskrelease> selectTaskreleases(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        ReleaseUser releaseList = new ReleaseUser();
        if (taskrelease != null) {
            releaseList = taskreleaseMapper.selectUTaskrelease(taskrelease);
            if (releaseList == null) {
                rspMsg.setOK();
                rspMsg.setMsg("未找到相关任务");
                return rspMsg;
            }
            map.put("releaseList", releaseList);
            rspMsg.setOK();
            rspMsg.setResult(map);
        }
        return rspMsg;
    }

    // 查询任务详情
    @Override
    public RspMsg<Taskrelease> selectDetails(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        ReleaseUser releaseList = new ReleaseUser();
        if (releaseList != null) {
            releaseList = taskreleaseMapper.selectUTaskrelease(taskrelease);
            if (releaseList == null) {
                rspMsg.setOK();
                rspMsg.setMsg("未找到相关信息");
                return rspMsg;
            }
        }
        rspMsg.setOK();
        rspMsg.setResult(releaseList);
        return rspMsg;
    }

    // 审核通过
    @Override
    @Transactional
    public RspMsg<Taskrelease> auditTaskRelease(String taskReleaseId, String auditStates) {
        RspMsg rspMsg = new RspMsg();
        Taskrelease taskrelease = null;
        if (!taskReleaseId.equals("") && taskReleaseId != null) {
            taskrelease = taskreleaseMapper.selectByPrimaryKey(taskReleaseId);
        } else {
            rspMsg.setError();
            rspMsg.setMsg("任务ID为空!!!");
            return rspMsg;
        }

        taskrelease.setTaskStatus(auditStates);
        int i = taskreleaseMapper.updateByPrimaryKeySelective(taskrelease);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("更新信息失败");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setMsg("更新信息成功");
        return rspMsg;
    }

    // 根据任务状态查询
    @Override
    public RspMsg<Taskrelease> selectByStates(String taskStates) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        Taskrelease taskreleases = new Taskrelease();
        if (taskStates != null) {
            taskreleases = taskreleaseMapper.selectByStates(taskStates);
            if (taskreleases == null) {
                rspMsg.setOK();
                rspMsg.setMsg("未找到相关信息");
                return rspMsg;
            }
        }
        rspMsg.setOK();
        rspMsg.setResult(taskreleases);
        return rspMsg;
    }

    // 手机查看任务详情
    @Override
    public RspMsg<Taskrelease> selectDetailss(Taskrelease taskrelease) {
        ReleaseUser taskrelease1 = new ReleaseUser();
        Map<String, Object> map = new LinkedHashMap<>();
        RspMsg rspMsg = new RspMsg();
        String taskId = taskrelease.getTaskReleaseId();
        System.out.println(taskId);

        if (taskrelease != null) {
            taskrelease1 = taskreleaseMapper.selectUTaskrelease(taskrelease);
            if (taskrelease1 == null) {
                rspMsg.setError();
                rspMsg.setMsg("未找到相关信息");
                return rspMsg;
            }
            String userId = taskrelease1.getUserId();
            String taskReleaseId = taskrelease1.getTaskReleaseId();
            String orderid = taskrelease1.getUsersId();
            Example example = new Example(User.class);
            example.or().andEqualTo("userId", orderid);
            User user = userMapper.selectByExample(example).get(0);

            taskrelease1.setImagepath(user.getImagePath());
            taskrelease1.setUsernames(user.getUsername());

		/*	UserPay userPay	= userPayMapper.selectPayUser(userId,taskReleaseId);
			if(userPay == null){
				taskrelease1.setPhone("");
			}*/

            map.put("taskrelease", taskrelease1);
            rspMsg.setOK();
            rspMsg.setResult(map);
            return rspMsg;

            /*}*/
        }
        rspMsg.setOK();
        rspMsg.setMsg("未获取参数");
        return rspMsg;
    }

    //支付金币
    @Override
    public RspMsg<Taskrelease> payGold(String userId, String taskReleaseId, String payPassword) {
        RspMsg rspMsg = new RspMsg();
        User user = userMapper.selectByPrimaryKey(userId);
        Integer paygold = Integer.parseInt(user.getPayGold()) - 10;
        if (paygold < 0) {
            rspMsg.setError();
            rspMsg.setMsg("账户金币不足,请充值");
            return rspMsg;
        }
        if (!Md5Utils.encryptPassword(payPassword, user.getSalt()).equals(user.getPayPassword())) {
            rspMsg.setError();
            rspMsg.setMsg("支付密码,请重新输入");
            return rspMsg;
        } else {
            user.setPayGold(Integer.toString(paygold));
            int i = userMapper.updateByPrimaryKeySelective(user);
            if (i == 0) {
                rspMsg.setError();
                rspMsg.setMsg("支付失败");
                return rspMsg;
            }
            Taskrelease taskrelease = taskreleaseMapper.selectByPrimaryKey(taskReleaseId);
            OrderSheet orderSheet = new OrderSheet();
            orderSheet.setOrderId(UuidUtils.getNumberId(10));
            orderSheet.setOrderNo(UuidUtils.getdates() + UuidUtils.getNumberId(3));
            orderSheet.setTaskReleaseName(taskrelease.getTaskReleaseName());
            orderSheet.setPayGold("10");
            orderSheet.setUserId(userId);
            int j = orderSheetMapper.insertSelective(orderSheet);
            if (j == 0) {
                rspMsg.setError();
                rspMsg.setMsg("添加到订单表失败");
                return rspMsg;
            }
            rspMsg.setOK();
            rspMsg.setMsg("支付成功");
            return rspMsg;
        }

    }

    // 根据用户id查询订单详情
    @Override
    public RspMsg<OrderSheet> orderDetails(String userId) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        OrderSheet oderSheet = orderSheetMapper.orderDetails(userId);
        if (oderSheet == null || "".equals(oderSheet)) {
            rspMsg.setOK();
            rspMsg.setMsg("未查询到数据");
            return rspMsg;
        }
        map.put("oderSheetlist", oderSheet);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    //任务抢单
    @Override
    public RspMsg<Taskrelease> Robbing(String taskReleaseId, String userId) {
        RspMsg rspMsg = new RspMsg();
        Taskrelease taskrelease = taskreleaseMapper.selectByPrimaryKey(new Taskrelease().setTaskReleaseId(taskReleaseId));
        if (taskrelease.getTaskStatus().equals("3")) {
            rspMsg.setError();
            rspMsg.setMsg("此订单已被抢");
        } else {
            taskrelease.setTaskStatus("3");
            taskrelease.setTaskorderStatus("6");
            taskrelease.setRemark2(userId);
            taskreleaseMapper.updateByPrimaryKeySelective(taskrelease);
            //发布人电话
            String phone = userMapper.selectByPrimaryKey(new User().setUserId(taskrelease.getUserId())).getPhone();
            //接单人电话
            //String RobbingPhone =  userMapper.selectByPrimaryKey(new User().setUserId(taskrelease.getRemark2())).getPhone();
            try {
                //发送短信通知
                int result = sendSMS(phone);
                rspMsg.setOK();
                rspMsg.setMsg("抢单成功");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }
        return rspMsg;
    }

    //手机端任务列表
    public RspMsg<Taskrelease> selectTaskRelease() {
        Map<String, Object> map = new LinkedHashMap<>();
        RspMsg rspMsg = new RspMsg();
        List<Taskrelease> taskrelease1 = taskreleaseMapper.selectTaskRelease();
        map.put("taskreleaseList", taskrelease1);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    //手机端首页任务列表
    public RspMsg<Taskrelease> selectTaskReleaseIndex(int i) {
        Map<String, Object> map = new LinkedHashMap<>();
        RspMsg rspMsg = new RspMsg();
        List<Taskrelease> taskrelease1 = taskreleaseMapper.selectTaskReleaseIndex(i);
        map.put("taskreleaseList", taskrelease1);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }


    //查询用户发布的所有任务
    @Override
    public RspMsg<Taskrelease> selectUserTaskRelease(Taskrelease Taskrelease) {
        Map<String, Object> map = new LinkedHashMap<>();
        RspMsg rspMsg = new RspMsg();
        Example example = new Example(Taskrelease.class);
        example.or().andEqualTo("userId", Taskrelease.getUserId());
        List<Taskrelease> taskrelease1 = taskreleaseMapper.selectByExample(example);
        map.put("taskreleaseList", taskrelease1);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    //查询用户接单的所有任务
    @Override
    public RspMsg<Taskrelease> selectUserTaskOrder(Taskrelease Taskrelease) {
        Map<String, Object> map = new LinkedHashMap<>();
        RspMsg rspMsg = new RspMsg();
        Example example = new Example(Taskrelease.class);
        example.or().andEqualTo("remark2", Taskrelease.getUserId());
        List<Taskrelease> taskrelease1 = taskreleaseMapper.selectByExample(example);
        map.put("taskreleaseList", taskrelease1);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    /**
     * 手机端根据任务单号查看任务详情，任务接单人
     *
     * @param
     * @return
     */
    @Override
    public RspMsg<Taskrelease> selectByTaskIdTaskRelease(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        ReleaseUser releaseUser = new ReleaseUser();
        if (null != taskrelease.getUserId()) {
            releaseUser = taskreleaseMapper.selectByTaskIdTaskRelease(taskrelease);
        } else {
            releaseUser = taskreleaseMapper.selectByTaskIdTaskRelease1(taskrelease);
        }
        if (releaseUser == null) {
            rspMsg.setError();
            rspMsg.setMsg("未找到相关数据");
        } else {
            rspMsg.setOK();
            rspMsg.setResult(releaseUser);
        }
        return rspMsg;
    }

    @Override
    public Taskrelease selectTaskByTaskId(String userId) {
        return null;
    }

    /**
     * 根据任务id 查询任务
     *
     * @param taskrelease
     * @return
     */
    public RspMsg<Taskrelease> selectTaskIdTaskRelease(Taskrelease taskrelease) {
        RspMsg rspMsg = new RspMsg();
        Taskrelease taskrelease1 = taskreleaseMapper.selectByPrimaryKey(taskrelease);
        if (taskrelease != null) {
            rspMsg.setOK();
            rspMsg.setResult(taskrelease1);
        } else {
            rspMsg.setError();
        }
        return rspMsg;

    }


    /**
     * 短信通知接口
     *

     * @return
     * @throws HttpException
     * @throws IOException
     */
    public int sendSMS(String phone) throws HttpException, IOException {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://160.19.212.218:8080/eums/send_strong.do");
        String now = getStringDate();

        String key = Md5Utils.GetMD5Code(Md5Utils.GetMD5Code("68hp3fy") + now);
        post.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
        post.setRequestHeader("Connection", "close");
        NameValuePair[] data = {new NameValuePair("name", "sxyjyzm"),
                new NameValuePair("seed", now),
                new NameValuePair("key", key),
                new NameValuePair("dest", phone),
                new NameValuePair("content", "【银信科技】您发布的订单已被接单，请登录平台查看接单人详细资料，并确认")};
        post.setRequestBody(data);
        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        System.out.println("========>" + result);
        post.releaseConnection();
        return 1;
    }


    /**
     * 短信通知接口
     *
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public int sendSMStask(String phone, String coode) throws HttpException, IOException {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://160.19.212.218:8080/eums/send_strong.do");
        String now = getStringDate();
        String key = Md5Utils.GetMD5Code(Md5Utils.GetMD5Code("68hp3fy") + now);
        post.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
        post.setRequestHeader("Connection", "close");
        NameValuePair[] data = {new NameValuePair("name", "sxyjyzm"),
                new NameValuePair("seed", now),
                new NameValuePair("key", key),
                new NameValuePair("dest", phone),
                new NameValuePair("content", "【银信科技】验证码：" + coode + ",请收藏好您的验证码，交易完成后，将验证码提供给接单人员，即完成付款操作。")};
        post.setRequestBody(data);
        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        System.out.println("========>" + result);
        post.releaseConnection();
        return 1;
    }


}
